//
//  LxWaterFlowLayout.swift
//  七哥直播
//
//  Created by 七 on 2017/12/20.
//  Copyright © 2017年 seven. All rights reserved.
//

import UIKit

protocol LxWaterFlowLayoutDataSource: class {
    func numberOfCols(_ waterfall: LxWaterFlowLayout) -> Int
    func waterfall(_ waterfall: LxWaterFlowLayout, heightForItemAt indexPath: IndexPath) -> CGFloat
}

class LxWaterFlowLayout: UICollectionViewFlowLayout {
    weak var dataSource: LxWaterFlowLayoutDataSource?
    private lazy var cellAttrs: [UICollectionViewLayoutAttributes] = [UICollectionViewLayoutAttributes]()
    private lazy var cols: Int = {
        return self.dataSource?.numberOfCols(self) ?? 0
    }()
    private lazy var totalHeight: [CGFloat] = {
        let cols = self.dataSource?.numberOfCols(self) ?? 2
        var totalHeight = Array(repeating: self.sectionInset.top, count: cols)
        return totalHeight
    }()
    private var startIndex: Int = 0
}

//MARK:- 准备布局
extension LxWaterFlowLayout{
    override func prepare() {
        //1.获取item的个数
        let itemCount = collectionView!.numberOfItems(inSection: 0)
        let cellW: CGFloat = (collectionView!.bounds.width - sectionInset.left - sectionInset.right - minimumInteritemSpacing * CGFloat(cols - 1)) / CGFloat(cols)
        //2.获取item对应的indexpath
        for i in startIndex ..< itemCount{
            let indexPath = IndexPath(item: i, section: 0)
            //3.获取对应item的attributes
            let attr = UICollectionViewLayoutAttributes(forCellWith: indexPath)
            
            guard let cellH: CGFloat = dataSource?.waterfall(self, heightForItemAt: indexPath) else {
                fatalError("请实现对应的数据源方法，并返回Cell高度")
            }
            let minCellH = totalHeight.min()!
            let minIndex = totalHeight.index(of: minCellH)!
            let cellX: CGFloat = sectionInset.left + (cellW + minimumInteritemSpacing) * CGFloat(minIndex)
            let cellY: CGFloat = minCellH
            attr.frame = CGRect(x: cellX, y: cellY, width: cellW, height: cellH)
            cellAttrs.append(attr)
            totalHeight[minIndex] = minCellH + cellH + minimumLineSpacing
        }
        //给startIndex重新赋值
        startIndex = itemCount
    }
}

//MARK:- 返回准备好的所有布局
extension LxWaterFlowLayout{
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        return cellAttrs
    }
}

//MARK:- 设置collectionview的contentSize
extension LxWaterFlowLayout{
    override var collectionViewContentSize: CGSize{
        return CGSize(width: 0, height: totalHeight.max()! + sectionInset.bottom)
    }
}
